<?php

namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Validate;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Operatecenter extends Backend
{

    /**
     * Operatecenter模型对象
     * @var \app\admin\model\Operatecenter
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Operatecenter;
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->view->assign("typeList", $this->model->getTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $newwhere = [];
            $item = Db::name('address_location')->where('adminid',$this->auth->id)->find();
            if($this->auth->type=="company"){
                $newwhere['yz_address_location.city_id'] = $item['city_id'];
            }elseif($this->auth->type=="operatecenter"){
                $newwhere['yz_address_location.region_id'] = $item['region_id'];
            }
            $list = $this->model
                    ->with(['admin','user'])
                    ->where($where)
                ->where('operatecenter.type','operatecenter')
                ->where($newwhere)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('admin')->visible(['username','nickname','mobile','logintime','loginip']);
				$row->getRelation('user')->visible(['money']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $item = Db::name('address_location')->where(array('province_id'=>$params['province_id'],'city_id'=>$params['city_id'],'region_id'=>$params['region_id'],'type'=>'operatecenter'))->find();
            if(!empty($item)){//查询该社区是否已有人管理.
                $this->error('该地区已有运营中心,请勿重复添加');
            }
            $userItem = Db::name('user')->where('mobile',$params['mobile'])->find();
            if(empty($userItem)){
                $this->error('该手机号未注册');
            }
            //该手机号已有运营中心不可重复添加
            $finduseraddress = Db::name('address_location')->where(array('uid'=>$userItem['id'],'type'=>'operatecenter'))->find();
            if(!empty($finduseraddress)){
                $this->error('该用户已有运营中心不可重复添加');
            }
            try {
                Db::startTrans();
                //查询手机号是否是前台用户
                $params['uid'] = $userItem['id'];
                //账号密码存到管理员表
                if (!Validate::is($params['password'], '\S{6,30}')) {
                    exception(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $admindata = [
                    'username'=>$params['username'],
                    'nickname'=>$params['nickname'],
                    'password'=>$params['password'],
                    'salt'=>$params['salt'],
                    'type'=>'operatecenter',
                    'mobile'=>$params['mobile']
                ];
                $result = model('Admin')->save($admindata);//管理员表
                if ($result === false) {
                    exception($this->model->getError());
                }
                $group = $this->request->post("group/a");
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                if (!$group) {
                    exception(__('The parent group exceeds permission limit'));
                }
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => model('Admin')->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);//权限保存
                $province = Db::name('area')->where(array('id'=>$params['province_id']))->find();
                $params['province'] = $province['name'];
                //查询市名
                $city = Db::name('area')->where(array('id'=>$params['city_id']))->find();
                $params['city'] = $city['name'];
                //查询区名
                $county = Db::name('area')->where(array('id' => $params['region_id']))->find();
                $params['county'] = !empty($county['name']) ? $county['name'] : '-';
                $quyudata = [
                    'uid'=>$userItem['id'],
                    'type'=>'operatecenter',
                    'province'=>$params['province'],
                    'city'=>$params['city'],
                    'county'=>$params['county'],
                    'province_id'=>$params['province_id'],
                    'city_id'=>$params['city_id'],
                    'region_id'=>$params['region_id'],
                    'free'=>1,
                    'adminid'=>model('Admin')->id
                ];
                //区域信息存到区域表
                $result = $this->model->save($quyudata);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model
            ->alias('c')
            ->join('admin a','c.adminid=a.id','LEFT')
            ->field('c.*,a.nickname,a.username,a.mobile')
            ->where(['c.id' => $ids])
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            $item = Db::name('address_location')->where(array('province_id'=>$params['province_id'],'city_id'=>$params['city_id'],'region_id'=>$params['region_id'],'type'=>'operatecenter'))
                ->where('id','neq',$row['id'])
                ->find();
            if(!empty($item)){//查询该社区是否已有人管理.
                $this->error('该地区已有运营中心,请勿重复添加');
            }
            $userItem = Db::name('user')->where('mobile',$params['mobile'])->find();
            if(empty($userItem)){
                $this->error('该手机号未注册');
            }
            //该手机号已有分公司不可重复添加
            $finduseraddress = Db::name('address_location')->where(array('uid'=>$userItem['id'],'type'=>'operatecenter'))
                ->where('id','neq',$row['id'])
                ->find();
            if(!empty($finduseraddress)){
                $this->error('该用户已有运营中心不可重复添加');
            }
            if ($params) {
                Db::startTrans();
                try {
//查询手机号是否是前台用户
                    $params['uid'] = $userItem['id'];
                    $admindata = [
                        'username'=>$params['username'],
                        'nickname'=>$params['nickname'],
                        'type'=>'company',
                        'mobile'=>$params['mobile']
                    ];
                    //账号密码存到管理员表
                    if ($params['password']) {
                        if (!Validate::is($params['password'], '\S{6,30}')) {
                            exception(__("Please input correct password2"));
                        }
                        $admindata['salt'] = Random::alnum();
                        $admindata['password'] = md5(md5($params['password']) . $admindata['salt']);
                    }

                    $result = model('Admin')->save($admindata,array('id'=>$row['adminid']));//修改管理员表
                    if ($result === false) {
                        exception($this->model->getError());
                    }
                    // 先移除所有权限
                    model('AuthGroupAccess')->where('uid', $row['adminid'])->delete();
                    $group = $this->request->post("group/a");
                    //过滤不允许的组别,避免越权
                    $group = array_intersect($this->childrenGroupIds, $group);
                    if (!$group) {
                        exception(__('The parent group exceeds permission limit'));
                    }
                    $dataset = [];
                    foreach ($group as $value) {
                        $dataset[] = ['uid' => $row['adminid'], 'group_id' => $value];
                    }
                    model('AuthGroupAccess')->saveAll($dataset);//权限保存

                    $province = Db::name('area')->where(array('id'=>$params['province_id']))->find();
                    $params['province'] = $province['name'];
                    //查询市名
                    $city = Db::name('area')->where(array('id'=>$params['city_id']))->find();
                    $params['city'] = $city['name'];
                    //查询区名
                    $county = Db::name('area')->where(array('id' => $params['region_id']))->find();
                    $params['county'] = !empty($county['name']) ? $county['name'] : '-';
                    $quyudata = [
                        'uid'=>$userItem['id'],
                        'type'=>'operatecenter',
                        'province'=>$params['province'],
                        'city'=>$params['city'],
                        'county'=>$params['county'],
                        'province_id'=>$params['province_id'],
                        'city_id'=>$params['city_id'],
                        'region_id'=>$params['region_id'],
                        'free'=>1,
                    ];
                    //区域信息存到区域表
                    $result = $this->model->save($quyudata,array('id'=>$row['id']));
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $grouplist = $this->auth->getGroups($row['adminid']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");//公司的ID
        if ($ids) {
            $adminList = \app\admin\model\Company::
            field('id,uid,adminid')
                ->where('id', 'in', $ids)
                ->select();
            $AdminIds = [];
            foreach ($adminList as $k => $v) {
                $AdminIds[] = $v['adminid'];
            }
            Db::startTrans();
            try {
                //删除公司信息
                $this->model->destroy($ids);
                //删除管理员
                model('Admin')->destroy($AdminIds);
                //删除管理员权限
                model('AuthGroupAccess')->where('uid', 'in', $AdminIds)->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('You have no permission'));
    }
}


